package com.action.gulimall.member.interceptor;

import com.action.common.constant.AuthServerConstant;
import com.action.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sl shilun217@qq.com
 * @Deacription 登录拦截器，没有登录的请求需要先去登录
 * @date 2021/07/03/15:12
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        boolean match = new AntPathMatcher().match("/member/**", request.getRequestURI());
        if(match){
            return true;
        }
        //alipay.trade.page.pay.return
        String method = request.getParameter("method");
        if("alipay.trade.page.pay.return".equals(method)){
            return true;
        }
//        int indexOf = request.getRequestURL().indexOf("method=alipay.trade.page.pay.return");
//        if(indexOf!=-1){
//            return true;
//        }
        MemberResponseVo memberResponseVo = (MemberResponseVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if(memberResponseVo!=null){
            threadLocal.set(memberResponseVo);
            return true;
        }else{
            //去登录
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }

    }
}
